<template>
    <div>
        <el-card shadow="hover" style="margin-bottom: 20px;">
            <el-form label-width="70px" class="demo-form-inline" :model="spu">
                <el-form-item label="SPU名称">
                    <el-input placeholder="请输入SPU名称" style="width:200px" v-model="spu.spuName"></el-input>
                </el-form-item>

                <el-form-item label="品牌名称">
                    <el-select placeholder="请选择品牌名称" v-model="spu.tmId">
                        <el-option :label="tm.tmName" :value="tm.id" v-for="tm in tradeMarkList" :key="tm.tmId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="SPU描述">
                    <el-input style="width:100%" type="textarea" :rows="10" placeholder="SPU描述"
                        v-model="spu.description">
                    </el-input>
                </el-form-item>
                <el-form-item label="SPU图片">
                    <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="spuImageList"
                        :on-success="handlerSuccess">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
                <el-form-item label="销售属性">
                    <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
                        <el-option :label="unselect.name" :value="`${unselect.id}:${unselect.name}`"
                            v-for="unselect in unSelectSaleAttr" :key="unselect.id"></el-option>
                    </el-select>
                    <el-button type="primary" icon="el-icon-plus" style="margin-left:20px" @click="addunselect">添加销售属性
                    </el-button>
                </el-form-item>
                <el-table :data="spu.spuSaleAttrList" stripe style="width: 100%;margin-left: 70px;">
                    <el-table-column type="index" label="序号" width="180" align="center">
                    </el-table-column>
                    <el-table-column prop="saleAttrName" label="属性名" width="180" align="center">
                    </el-table-column>
                    <el-table-column prop="address" label="属性值名称列表" align="center">
                        <template slot-scope="{ row }">
                            <el-tag v-for="tag, index in row.spuSaleAttrValueList" :key="tag.id" closable
                                style="margin-left:20px" :type="tag.type" :disable-transitions="false"
                                @close="row.spuSaleAttrValueList.splice(index, 1)">
                                {{ tag.saleAttrValueName }}
                            </el-tag>
                            <el-input v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small"
                                @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm(row)"
                                style="width:50px;margin-left:20px"></el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)"
                                style="margin-left:20px">添加</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="address" label="操作" align="center">
                        <template slot-scope="{ row,$index }">
                            <el-button type="danger" icon="el-icon-delete" size="mini"
                                @click="deleteSaleAttr(row, $index)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="success" style="margin-left:70px;margin-top: 20px;" icon="el-icon-folder-add" @click="addOrUpdateSpu">保存
                </el-button>
                <el-button type="info" style="margin-top: 20px;" icon="el-icon-folder-delete" @click="info">取消
                </el-button>
            </el-form>

        </el-card>
    </div>
</template>

<script>
export default {
    name: 'SpuForm',
    data() {
        return {
            datainput: "",
            dialogImageUrl: "",
            dialogVisible: false,
            spu: {
                //三级分类的id
                category3Id: 0,
                //描述
                description: "",
                //spu名称
                spuName: "",
                //平台的id
                tmId: "",
                //收集SPU图片的信息
                spuImageList: [
                    // {
                    //   id: 0,
                    //   imgName: "string",
                    //   imgUrl: "string",
                    //   spuId: 0,
                    // },
                ],
                //平台属性与属性值收集
                spuSaleAttrList: [
                    // {
                    //   baseSaleAttrId: 0,
                    //   id: 0,
                    //   saleAttrName: "string",
                    //   spuId: 0,
                    //   spuSaleAttrValueList: [
                    //     {
                    //       baseSaleAttrId: 0,
                    //       id: 0,
                    //       isChecked: "string",
                    //       saleAttrName: "string",
                    //       saleAttrValueName: "string",
                    //       spuId: 0,
                    //     },
                    //   ],
                    // },
                ],
            },
            tradeMarkList: [],
            spuImageList: [],
            saleAttrList: [],
            attrIdAndAttrName: ''
        };
    },
    computed: {
        unSelectSaleAttr() {
            let result = this.saleAttrList.filter(item => {
                return this.spu.spuSaleAttrList.every(item1 => {
                    return item.name != item1.saleAttrName
                })
            })
            return result
        }
    },
    methods: {
        handleRemove(file, fileList) {
            console.log(file, fileList);
            
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handlerSuccess(response, file, fileList) {
            this.spuImageList = fileList
        },
        async getData(category3Id){
            this.spu.category3Id = category3Id;
             let traderesult = await this.$API.reqtradeMarkList()
            if (traderesult.code == 200) {
                this.tradeMarkList = traderesult.data
            };
            let saleresult = await this.$API.reqBaseSaleAttrList()

            if (saleresult.code == 200) {
                this.saleAttrList = saleresult.data
            }
        },
        async initSpuData(spu) {
            let spuresult = await this.$API.reqSpu(spu.id)
            if (spuresult.code == 200) {
                this.spu = spuresult.data;
            }
            let traderesult = await this.$API.reqtradeMarkList()
            if (traderesult.code == 200) {
                this.tradeMarkList = traderesult.data
            };
            let spuImageResult = await this.$API.reqSpuImageList(spu.id)
            if (spuImageResult.code == 200) {
                let listArr = spuImageResult.data
                listArr.forEach(item => {
                    item.name = item.imgName;
                    item.url = item.imgUrl
                });
                this.spuImageList = listArr
            };
            let saleresult = await this.$API.reqBaseSaleAttrList()

            if (saleresult.code == 200) {
                this.saleAttrList = saleresult.data
            }
        },

        info() {
           
            this.$emit('change',0)
            Object.assign(this._data, this.$options.data());
        },
        addunselect() {
            let [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
            const newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
            this.spu.spuSaleAttrList.push(newSaleAttr)
        },
        addSaleAttrValue(row) {
            this.$set(row, 'inputVisible', true)
            this.$set(row, 'inputValue', '')
            this.$nextTick(() => {
                this.$refs.saveTagInput.focus();
            })
        },
        handleInputConfirm(row) {
            const { baseSaleAttrId, inputValue } = row;
            if (inputValue.trim() == '') {
                this.$message('属性值不能为空');
                return;
            }
            let result = row.spuSaleAttrValueList.every(item => item.saleAttrValueName != inputValue)
            if (!result) { this.$message.error('属性名不能重复') } else {
                let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
                row.spuSaleAttrValueList.push(newSaleAttrValue)
                row.inputVisible = false
            }

        },
        deleteSaleAttr(row, index) {
            this.spu.spuSaleAttrList.splice(index, 1)
        },
        async addOrUpdateSpu() {
      //整理参数：需要整理照片墙的数据
      //携带参数：对于图片，需要携带imageName与imageUrl字段
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url,
        };
      });
      //发请求
      let result = await this.$API.reqAddOrUpdateSpu(this.spu);
      if (result.code == 200) {
          
        //通知父组件回到场景0
        this.$emit("changeInfo", {
          Scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
      }
      //清除数据
      Object.assign(this._data, this.$options.data());
    },
    }
}
</script>

<style>
</style>